package com.yunao.service.report.esou;


import com.yunao.entity.AloneReport;
import com.yunao.entity.Report;
import com.yunao.service.ReportService;
import com.yunao.service.report.info.MailService;
import com.yunao.service.report.info.factory.InfoFactory;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 自动报告线程
 *
 * @author glt
 *
 */
public class ReportThread2 implements Runnable {

	private List<AloneReport> aloneReports;
	private ReportService reportService;
	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

	public ReportThread2(List<AloneReport> aloneReports,ReportService reportService) {
		this.aloneReports = aloneReports;
		this.reportService = reportService;
	}

	public List<Report> queryReportByname(Report report, Integer userId){
		List<Report> reports = reportService.findAllByNameAndUserId(report.getName(),userId);
		return reports;
	}

	public List<Report> queryReport(String reportname,String addrs){
		List<Report> reports = reportService.findAllByNameAndAddrs(reportname,addrs);
		return reports;
	}
	public void run() {
//		DbUtil util = DbUtil.getInstance();
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());

		int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
		int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
		int dayOfYear = c.get(Calendar.DAY_OF_YEAR);
		int weekOfYear = c.get(Calendar.WEEK_OF_YEAR);
		int month = c.get(Calendar.MONTH)+1;
		MailService mail = InfoFactory.getMail();
		int i=0;

		for (AloneReport aloneReport : aloneReports) {
			System.out.println("----reproting----"+i++);
			// 自动报告方式
			String manner = aloneReport.getReportmanner();
			String addrs=aloneReport.getReportaddrs();
			// 日报
			if (manner.equals("1") || manner.equals("3") || manner.equals("5") || manner.equals("7")) {
				ReportDaily2 daily = new ReportDaily2(aloneReport,reportService);
				Report report = new Report();
				try {
					String docName = aloneReport.getName() + "第" + dayOfYear + "期日报";
					List<Report> reportlist = queryReport(docName,aloneReport.getReportaddrs());
					if(reportlist.size()==0){
						report.setName(docName);
						String docPath = daily.createMailc();
						String mailtext=daily.createHtmlword();
						report.setFilePath(docPath);
						Map<String, String> attachment = new HashMap<String, String>();
						attachment.put(docName + ".doc", docPath);
						String text = daily.createHtml();
//						String mailtextstr = "/a><br><br>如果不希望收到该报告，请点<a href='http://www.yunaodata.com/report_unsubscribe.do?id="+Hex.encodeHexString(String.valueOf(aloneReport.getId()).getBytes())+"&addr="+Hex.encodeHexString(addrs.getBytes())+"'>取消订阅<";
						String mailtextstr = "/a><br><br>如果不希望收到该报告，可前往后台系统取消订阅<";
						mail.sendMail(docName, new String[]{addrs}, mailtext + mailtextstr, attachment);

						report.setSendResult(1);
						report.setText(text);

						report.setManner(1);
						report.setCreateDate(simpleDateFormat.format(new Date()));
						report.setAddrs(aloneReport.getReportaddrs());
						report.setAloneReportId(aloneReport.getId());
						report.setUserId(aloneReport.getUserId());
						report.setOrganizationId(Integer.parseInt(aloneReport.getSubjectOrganizationId()));
						List<Report> reports = queryReportByname(report,aloneReport.getUserId());
						if(reports.size()==0){
//					util.save(report);
							reportService.save(report);
						}else{
							reports.get(0).setAddrs(report.getAddrs());
//					util.update(reports.get(0));
							reportService.saveOrUpdate(reports.get(0));
						}
						this.log("【" + aloneReport.getName() + "】日报发送完成------1");
					}else{
						this.log("【" + aloneReport.getName() + "】日报已发送过------1");
					}

				} catch (Exception e) {
					e.printStackTrace();
					String docName = aloneReport.getName() + "第" + dayOfYear + "期日报";
					report.setName(docName);
					report.setText(report.getText()+e.getMessage());
					report.setSendResult(0);
					report.setManner(1);
					report.setCreateDate(simpleDateFormat.format(new Date()));
					report.setAddrs(aloneReport.getReportaddrs());
					report.setAloneReportId(aloneReport.getId());
					report.setUserId(aloneReport.getUserId());
					report.setOrganizationId(Integer.parseInt(aloneReport.getSubjectOrganizationId()));
					reportService.save(report);
					List<Report> reports = queryReportByname(report,aloneReport.getUserId());
					if(reports.size()==0){
//					util.save(report);
						reportService.save(report);
					}else{
						reports.get(0).setAddrs(report.getAddrs());
//					util.update(reports.get(0));
						reportService.saveOrUpdate(reports.get(0));
					}
				}

			}

			// 周报
			if (manner.equals("2") || manner.equals("3") || manner.equals("6") || manner.equals("7") && dayOfWeek == Calendar.MONDAY) {
//			if (manner.equals("2") || manner.equals("3") || manner.equals("6") || manner.equals("7") ) {
				ReportWeekly2 weekly = new ReportWeekly2(aloneReport,reportService);
				Report report = new Report();
				try {
					String docName = aloneReport.getName() + "第" + weekOfYear + "期周报";
					System.out.println("add:"+aloneReport.getReportaddrs());
					List<Report> reportlist = queryReport(docName,aloneReport.getReportaddrs());
					if(reportlist.size()==0){
						report.setName(docName);
						String docPath = weekly.createMailc();
						String mailtext=weekly.createHtmlword();
						report.setFilePath(docPath);
						Map<String, String> attachment = new HashMap<String, String>();
						attachment.put(docName + ".doc", docPath);
//							String mailtextstr = "<br>如果不希望收到该报告，请点<a href='http://www.yunaodataaodata.com/report_unsubscribe.do?id="+Hex.encodeHexString(String.valueOf(aloneReport.getId()).getBytes())+"&addr="+Hex.encodeHexString(addrs.getBytes())+"'>取消订阅</a><br>";
						String mailtextstr = "/a><br><br>如果不希望收到该报告，可前往后台系统取消订阅<";
						mail.sendMail(docName, new String[]{addrs}, mailtext + mailtextstr, attachment);
						String text = weekly.createHtml();
						report.setText(text);
						report.setSendResult(1);

						report.setManner(2);
						report.setCreateDate(simpleDateFormat.format(new Date()));
						report.setAddrs(aloneReport.getReportaddrs());
						report.setAloneReportId(aloneReport.getId());
						report.setUserId(aloneReport.getUserId());
						report.setOrganizationId(Integer.parseInt(aloneReport.getSubjectOrganizationId()));


						List<Report> reports = queryReportByname(report,aloneReport.getUserId());
						if(reports.size()==0){
//					util.save(report);
							reportService.save(report);
						}else{
							reports.get(0).setAddrs(report.getAddrs());
//					util.update(reports.get(0));
							reportService.saveOrUpdate(reports.get(0));
						}

						this.log("【" + aloneReport.getName() + "】周报发送完成------1");
					}else{
						this.log("【" + aloneReport.getName() + "】周报已发送过------1");
					}

				} catch (Exception e) {
					String docName = aloneReport.getName() + "第" + weekOfYear + "期周报";
					report.setName(docName);
					report.setText(report.getText()+e.getMessage());
					report.setSendResult(0);
					report.setManner(2);
					report.setCreateDate(simpleDateFormat.format(new Date()));
					report.setAddrs(aloneReport.getReportaddrs());
					report.setAloneReportId(aloneReport.getId());
					report.setUserId(aloneReport.getUserId());
					report.setOrganizationId(Integer.parseInt(aloneReport.getSubjectOrganizationId()));
					List<Report> reports = queryReportByname(report,aloneReport.getUserId());
					if(reports.size()==0){
						reportService.save(report);
					}else{
						//System.out.println("reports:"+reports.get(0).getName());
						reports.get(0).setAddrs(report.getAddrs());
						reportService.saveOrUpdate(reports.get(0));
					}
					this.log("【" + aloneReport.getName() + "】周报发送异常-------1");
				}


			}
			// 月报
			if (manner.equals("4") || manner.equals("5") || manner.equals("6") || manner.equals("7") && dayOfMonth == 1) {
//			if (manner.equals("4") || manner.equals("5") || manner.equals("6") || manner.equals("7")) {
				ReportMonthly2 monthly = new ReportMonthly2(aloneReport,reportService);
				Report report = new Report();
				try {
					String docName = aloneReport.getName() + "第" + month + "期月报";
					System.out.println(docName);
					List<Report> reportlist = queryReport(docName,aloneReport.getReportaddrs());
					if(reportlist.size()==0){
						report.setName(docName);
						String docPath = monthly.createMailc();
						String mailtext= monthly.createHtmlword();
						report.setFilePath(docPath);
						Map<String, String> attachment = new HashMap<String, String>();
						attachment.put(docName + ".doc", docPath);
//						String mailtextstr = "<br>如果不希望收到该报告，请点<a href='http://www.yunaodata.com/report_unsubscribe.do?id="+Hex.encodeHexString(String.valueOf(aloneReport.getId()).getBytes())+"&addr="+Hex.encodeHexString(addrs.getBytes())+"'>取消订阅</a><br>";
						String mailtextstr = "/a><br><br>如果不希望收到该报告，可前往后台系统取消订阅<";
						mail.sendMail(docName, new String[]{addrs}, mailtext + mailtextstr, attachment);
						String text = monthly.createHtml();
						report.setText(text);
						report.setSendResult(1);
						this.log("【" + aloneReport.getName() + "】月报发送完成------1");

						report.setManner(4);
						report.setCreateDate(simpleDateFormat.format(new Date()));
						report.setAddrs(aloneReport.getReportaddrs());
						report.setAloneReportId(aloneReport.getId());
						report.setUserId(aloneReport.getUserId());
						report.setOrganizationId(Integer.parseInt(aloneReport.getSubjectOrganizationId()));
						List<Report> reports = queryReportByname(report,aloneReport.getUserId());
						if(reports.size()==0){
//					util.save(report);
							reportService.save(report);
						}else{
							reports.get(0).setAddrs(report.getAddrs());
//					util.update(reports.get(0));
							reportService.saveOrUpdate(reports.get(0));
						}
					}else{
						this.log("【" + aloneReport.getName() + "】月报已发送过------1");
					}

				} catch (Exception e) {
					String docName = aloneReport.getName() + "第" + month + "期月报";
					report.setName(docName);
					report.setText(report.getText()+e.getMessage());
					report.setSendResult(0);
					report.setManner(4);
					report.setCreateDate(simpleDateFormat.format(new Date()));
					report.setAddrs(aloneReport.getReportaddrs());
					report.setAloneReportId(aloneReport.getId());
					report.setUserId(aloneReport.getUserId());
					report.setOrganizationId(Integer.parseInt(aloneReport.getSubjectOrganizationId()));
					List<Report> reports = queryReportByname(report,aloneReport.getUserId());
					if(reports.size()==0){
						reportService.save(report);
					}else{
						//System.out.println("reports:"+reports.get(0).getName());
						reports.get(0).setAddrs(report.getAddrs());
						reportService.saveOrUpdate(reports.get(0));
					}
					this.log("【" + aloneReport.getName() + "】月报发送异常------1");
				}

			}
		}
	}

	public void log(String info) {
		System.out.println(info);
	}

}
